package cn.dankal.flyaudio.friend;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding2.view.RxView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.concurrent.TimeUnit;

import api.ShopUserServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.domain.HttpStatusCode;
import cn.dankal.basiclib.exception.LocalException;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.UserScoresEntity;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.contract.SendScorePresentContract;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.dankal.flyaudio.presenter.SendScorePresentPresenter;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class SendScorePresentActivity extends BaseActivity implements SendScorePresentContract.View, View.OnClickListener {

    public SendScorePresentPresenter presentPresenter;

    private EditText scoreView;

    private TextView myScoresView;

    private TextView scoreValueView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_score_present;
    }

    @Override
    protected void initComponents() {
        addSingleTitleBar("发积分红包");
        presentPresenter = new SendScorePresentPresenter();
        scoreView = findViewById(R.id.et_score);
        myScoresView = findViewById(R.id.tv_my_scores);
        scoreValueView = findViewById(R.id.tv_score_value);
        scoreView.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                scoreValueView.setText(s);
            }
        });
        myScoresView.setText(DKUserManager.getUserScores().getUsable());
        fetchUserScores();
        RxView.clicks(findViewById(R.id.tv_send_present)).throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String userScores = DKUserManager.getUserScores().getUsable();
                        if (TextUtils.isEmpty(userScores)) {
                            userScores = "0";
                        }
                        int scoresValue = Integer.parseInt(userScores);
                        String useScores = scoreView.getText().toString();
                        if (TextUtils.isEmpty(useScores)) {
                            ToastUtils.showShort("请输入要发送的积分");
                            return;
                        }
                        if (TextUtils.equals("0", useScores)) {
                            ToastUtils.showShort("发送积分最小为1");
                            return;
                        }
                        int useScoresValue = Integer.parseInt(useScores);
                        if (scoresValue < useScoresValue) {
                            ToastUtils.showShort("您的积分不够!");
                            return;
                        }
                        ConversationType convType = (ConversationType) getIntent().getSerializableExtra(FlyApplication.CONV_TYPE);
                        String targetId = getIntent().getStringExtra(FlyApplication.TARGET_ID);
                        String targetAppKey = getIntent().getStringExtra(FlyApplication.TARGET_APP_KEY);
                        Conversation conv = null;
                        if (convType != null) {
                            switch (convType) {
                                case single:
                                    doSendReq(useScores, targetId);
                                    break;
                                case group:
                                    doSendReqByGroup(useScores, targetId);
                                    break;
                                case chatroom:
                                    break;
                                default:
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presentPresenter.detachView();
    }

    @Override
    public void onClick(View v) {

    }

    private void doSendMessage(String id) {
        ConversationType convType = (ConversationType) getIntent().getSerializableExtra(FlyApplication.CONV_TYPE);
        String targetId = getIntent().getStringExtra(FlyApplication.TARGET_ID);
        String targetAppKey = getIntent().getStringExtra(FlyApplication.TARGET_APP_KEY);
        Conversation conv = null;
        if (convType != null) {
            switch (convType) {
                case single:
                    conv = JMessageClient.getSingleConversation(targetId, targetAppKey);
                    break;
                case group:
                    conv = JMessageClient.getGroupConversation(Long.valueOf(targetId));
                    break;
                case chatroom:
                    conv = JMessageClient.getChatRoomConversation(Long.valueOf(targetId));
                    break;
                default:
            }
        }
        CustomContent customContent = new CustomContent();
        customContent.setStringExtra("score", scoreView.getText().toString());
        customContent.setStringExtra("sendScore", "sendScore");
        customContent.setStringExtra("scoreGetId", id);
        Message textMessage = conv.createSendMessage(customContent);
        MessageSendingOptions options = new MessageSendingOptions();
        options.setNeedReadReceipt(true);
        JMessageClient.sendMessage(textMessage, options);
        textMessage.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    SharePreferenceManager.setIsOpen(true);
                    Toast.makeText(SendScorePresentActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.putExtra(FlyApplication.MSG_JSON, textMessage.toJson());
                    SendScorePresentActivity.this.setResult(RESULT_OK, intent);
                    finish();
                } else {
                    HandleResponseCode.onHandle(SendScorePresentActivity.this, i, false);
                }
            }
        });
    }
    public void fetchUserScores(){
        ShopUserServiceFactory.userScores().subscribe(new Observer<BaseResponse<UserScoresEntity>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse<UserScoresEntity> userScoresEntityBaseResponse) {
                DKUserManager.updateUserInfoScores(userScoresEntityBaseResponse.getData());
                LiveEventBus.get(LiveDataBusConstants.REFRESH_USER_SCORES, String.class).post("");
                myScoresView.setText(DKUserManager.getUserScores().getUsable());
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof LocalException) {
                    LocalException exception = (LocalException) e;
                    //401 重新获取access token , 如果还返回412 就是refresh token 也失效了。需要重新登录
                    if (exception.getErrorCode() == HttpStatusCode.TOKEN_INVAILD||
                            exception.getErrorCode() == HttpStatusCode.UNAUTHORIZED) {
                        //view.showToast("登录信息失效");
                    } else {
                    }
                } else {
                    Log.e("SubscriberThrowable", e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void doSendReq(String amount, String userUuid) {
        showLoadingDialog();
        ShopUserServiceFactory.userScores(amount, userUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        doSendMessage(objectBaseResponse.getData());
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }

    private void doSendReqByGroup(String amount, String groupId) {
        showLoadingDialog();
        ShopUserServiceFactory.userScoresByGroup(amount, groupId, "1")
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        doSendMessage(objectBaseResponse.getData());
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }
}
